from django.shortcuts import render
from django.views import View
from apps.areas.models import Area
from django.http import JsonResponse
from django.core.cache import cache
# Create your views here.


# 省级查询
class AreaTreeCleckView(View):
    def get(self, request):

        # 查询省
        data_sheng = Area.objects.filter(parent__isnull=True)

        # 验证
        if not data_sheng:
            return JsonResponse({'code': 400,
                                 'errmsg': '没有数据'})
        province_list = []
        for sheng in data_sheng:
            province_list.append({
                'id': sheng.id,
                'name': sheng.name
            })

        return JsonResponse({'code': 0,
                             'errmsg': 'ok',
                             'province_list': province_list})


# ======================================================================================================

# 查询市县
class AreaCityCleckView(View):
    def get(self, request, sheng_id):

        # 通过sheng_id查询shi
        son_data = cache.get('addr_%s' % sheng_id)




        try:
            parent_data = Area.objects.get(id=sheng_id)
            if not son_data:
                son_data = parent_data.subs.all()
            #else:
            #    son_data = son_data.decode()
        except Area.DoesNotExist:
            return JsonResponse({'code': 400,
                                'errmsg': '没有数据'})

        sub_data = []
        for sub in son_data:
            sub_data.append({
                'id': sub.id,
                'name': sub.name
            })

        data = {
            'code': 0,
            'errmsg': 'ok',
            'sub_data': {
                'id': parent_data.id,
                'name': parent_data.name,
                'subs': sub_data
                }
        }

        # 缓存数据
        cache.set('addr_%s' % sheng_id, son_data, 3600)

        return JsonResponse(data)









